<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\exception\UserException;
use app\admin\model\SystemGroup;
use app\admin\model\SystemUser;
use app\admin\validate\IDMustBePositiveInt;
use app\admin\validate\UserValidate;
use think\facade\Session;
use think\facade\View;
use think\Request;

class User extends Base
{
    public function info(Request $request){
        if($request->isPost()){
            (new UserValidate())->goCheck('edit');
            $params = $request->param();
            $data = [
                'name' => $params['name'],
                'nickname' => $params['nickname'],
                'contact_phone' => $params['contact_phone']
            ];
            $admin_id = Session::get('admin_id');
            $user = SystemUser::getUserByID($admin_id);
            if(!empty($params['old_password']) && !empty($params['new_password'])){
                //判断用户老密码是否正确
                if($user->password != md5($params['old_password'].$user->key)){
                    throw new UserException([
                        'msg' => '用户密码错误',
                        'errorCode' => 10104
                    ]);
                }
                //生成新的用户密钥和密码
                $data['key'] = getRandChar(16);
                $data['password'] = md5($params['new_password'].$data['key']);
            }

            $res = $user->save($data);
            if(!$res){
                throw new UserException([
                    'code' => 404,
                    'msg' => '修改用户信息失败',
                    'errorCode' => 10103
                ]);
            }
            return json([
                'msg' => '更新成功',
                'error_code' => 0
            ],200);
        }else{
            return View::fetch();
        }
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $user = SystemUser::getAllUserInfo();
        View::assign([
           'lists' => $user->toArray()
        ]);
        return View::fetch();
    }

    /**
     * @Descripttion:
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @author Siebe
     * @date 2022-02-19 1:17
     */
    public function add(Request $request)
    {
        //
        if($request->isPost()){
            (new UserValidate())->goCheck(UserValidate::Save);
            $params = $request->param();
            $params['key'] = getRandChar(16);
            $params['password'] = md5($params['password'].$params['key']);
            $params['login_times'] = 0;
            SystemUser::create($params,
                ['group_id','username','password','key','name','nickname','contact_phone','status','login_times']
            );
            return json([
                'msg' => '保存成功',
                'error_code' => 0
            ],200);
        }else{
            $group = SystemGroup::getAccessGroupInfo();
            View::assign([
                'group' => $group->toArray()
            ]);
            return View::fetch();
        }

    }

    /**
     * @Descripttion:
     * @param Request $request
     * @param $id
     * @return string|\think\response\Json
     * @throws UserException
     * @throws \app\lib\exception\ParameterException
     * @author Siebe
     * @date 2022-02-19 1:25
     */
    public function edit(Request $request, $id)
    {
        //
        (new IDMustBePositiveInt)->goCheck('check');
        $user = SystemUser::getUserInfoByID($id);
        if (!$user) {
            throw new UserException([
                'code' => 404,
                'msg' => '请传入用户ID',
                'errorCode' => 10102
            ]);
        }
        if ($request->isPost()) {
            (new UserValidate())->goCheck(UserValidate::Update);
            $params = $request->param();
            // 如果密码为空则不修改密码
            if(empty($params['password'])){
                unset($params['password']);
            }else{
                $params['password'] = md5($params['password'].$user->key);
            }
            $res = $user->save($params);
            if(!$res){
                throw new UserException([
                    'code' => 404,
                    'msg' => '修改用户信息失败',
                    'errorCode' => 10103
                ]);
            }
            return json([
                'msg' => '更新成功',
                'error_code' => 0
            ],200);
        } else {
            $group = SystemGroup::getAccessGroupInfo();
            View::assign([
                'user' => $user->toArray(),
                'group' => $group->toArray()
            ]);
            return View::fetch();
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        (new IDMustBePositiveInt)->goCheck('check');
        $user = SystemUser::find($id);
        if(!$user){
            throw new UserException([
                'code' => 404,
                'msg' => '请传入用户ID',
                'errorCode' => 10102
            ]);
        }
        if(!$user->delete()){
            throw new UserException([
                'code' => 404,
                'msg' => '删除用户失败',
                'errorCode' => 10105
            ]);
        }
        return json([
            'msg' => '删除成功',
            'error_code' => 0
        ],200);
    }
}
